package com.pc_project.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.pc_project.domain.Letter;
import com.pc_project.domain.Message;
import com.pc_project.domain.VO.JsonVO;
import com.pc_project.service.MessageService;
import com.pc_project.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

//import javax.management.remote.rmi._RMIConnection_Stub;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/message")
@Api(tags = "消息分组")
public class MessageController {

    @Autowired
    MessageService messageService;

    @ApiOperation("查询消息")
    @PostMapping("/queryMessage")
    public JsonVO<List<Message>> queryMessage(@RequestParam Integer lid) {
        List<Message> messages = messageService.queryMessage(lid);
        if(messages.isEmpty()) {
            return JsonVO.fail(messages);
        }
        return JsonVO.success(messages);
    }

    @ApiOperation("撤回消息")
    @PostMapping("/delete")
    public JsonVO<Boolean> delete(@RequestParam Integer mid) {
        Message message = messageService.queryMessageByMid(mid);
        if(message == null) {
            return JsonVO.fail(false);
        }
        messageService.deleteMessageByMid(mid);
        return JsonVO.success(true);
    }

    @ApiOperation("发送消息")
    @PostMapping("/sendMessage")
    public JsonVO<Boolean> sendMessage(@RequestParam Integer lid, @RequestParam String minfo, HttpServletRequest request){
        String token = request.getHeader("token");
        DecodedJWT decodedJWT = TokenUtils.parseJWT(token);
        Integer userId = Integer.valueOf(decodedJWT.getSubject());
        long currentTime = System.currentTimeMillis();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH时mm分ss秒");
        Date date = new Date(currentTime);
        Message message = new Message(null, lid, userId, 0, null, 0, minfo, date, null);
        boolean insert = messageService.insert(message);
        if(insert) {
            return JsonVO.success(true);
        }
        return JsonVO.fail(false);
    }

}
